import Component from "../Component.js";
import Type from "../../experience/db/Type.js";
import { _delay } from "../../experience/utils/F7.js";
import Filter from "./Filter.js";

export default class Manager extends Component{
    constructor() {
        super();

        this.xyz = false;
        this.mineCode = null;
        this.status = null
        this.currentId = 0;
        this.tunnelCode = '';
        this.tunnelName = '';
        this.pointIndex = 0;

        this.filter = new Filter();
    }

    async refresh() {
        const config = this.algo.getConfig();
        if (config == null) return;

        // 刷新巷道记录
        this.mineCode = config.mine_code;
        const filter1 = { mineCode: this.mineCode, tunnelName: "" };
        const tunnels = await this.api.getAllTunnelList(filter1);
        if (tunnels.code !== 0) {
            this.toast("获取巷道数据失败!");
            return;
        }
        await this.db.refresh(Type.Tunnel, tunnels.data);

        // 刷新导线点记录
        const filter2 = { mineCode: this.mineCode, tunnelCode: "" };
        const guildPoints = await this.api.getTunnelPointList(filter2);
        if (guildPoints.code !== 0) {
            this.toast("获取导线点数据失败!");
            return;
        }
        await this.db.refresh(Type.GuidePoint, guildPoints.data);
        await this.drawer.draw(Type.GuidePoint);
    }

    async init() {
        const config = this.algo.getConfig();
        if (config == null) return;

        this.mineCode = config.mine_code;
        const filter = { mineCode: this.mineCode, tunnelCode: this.tunnelCode };
        const resp = await this.api.getTunnelPointList(filter);
        if (resp.code !== 0) {
            this.toast("获取导线点失败!");
            return;
        }


        this.guildPoints = resp.data;
        this.$$("#tunnel-table").empty();
        for (let i = 0; i < this.guildPoints.length; i++) {
            const item = this.guildPoints[i];
            const id = `tunnel-table-${item.pointIndex}`;
            let tr = ``;
            if (i === 0) {
                this.pointIndex = item.pointIndex;
                this.currentId = item.id;
                tr= `
                     <tr class="selected" id="${id}">
                        <td class="numeric-cell">${item.pointIndex}</td>
                        <td class="numeric-cell">${item.x}</td>
                        <td class="numeric-cell">${item.y}</td>
                        <td class="numeric-cell">${item.z}</td>
                     </tr>
                `;
            } else {
                tr= `
                     <tr id="${id}">
                        <td class="numeric-cell">${item.pointIndex}</td>
                        <td class="numeric-cell">${item.x}</td>
                        <td class="numeric-cell">${item.y}</td>
                        <td class="numeric-cell">${item.z}</td>
                     </tr>
                `;
            }
            this.$$("#tunnel-table").append(this.$$(tr));
            this.$$('#' + id).on("click", () => {
                this.pointIndex = item.pointIndex;
                this.currentId = item.id;
                for (const item of this.guildPoints) {
                    const removeId = `tunnel-table-${item.pointIndex}`;
                    this.$$('#' + removeId).removeClass('selected')
                }
                this.$$('#' + id).addClass('selected');
            })
        }
    }

    async forms(name, s) {
        this.$$("#x").val("");
        this.$$("#y").val("");
        this.$$("#z").val("");
        this.$$("#ruler-length").val("");
        this.$$("#ruler-elevation").val("");
        this.$$("#ruler-azimuth").val("");
        this.$$("#ruler-timer").val("");
        this.$$("#ruler-code").val("");

        this.$$('#btn-tab-xyz').addClass('tab-link-active');
        this.$$('#tab-xyz').addClass('tab-active');
        this.$$('#btn-tab-ruler').removeClass('tab-link-active');
        this.$$('#tab-ruler').removeClass('tab-active');
        this.$$('#popup-header').html(name);
        this.$$('#btn-tab-ruler').show();

        this.xyz = true;
        this.status = s;
    }

    xyz() {
        this.$$('.xyz-popup').css('left', this.utils.left(460));
        this.xyzPopup = this.app.popup.create({ el: ".xyz-popup" });

        // 切换导线点输入方式
        this.$$('#btn-tab-xyz').on("click", () => this.xyz = true);
        this.$$('#btn-tab-ruler').on("click", () => this.xyz = false);
        this.$$("#ruler-time").val(this.utils.dateOfLocal());

        // 导线点增加
        this.$$('#tunnel-add').on("click", async () => {
            _delay('tunnel-add', async () => {
                await this.forms('增加导线点', 'add');

                if (this.guildPoints.length === 0) {
                    this.toast('无法通过进尺增加导线点。');
                    this.$$('#btn-tab-ruler').hide();
                }

                if (this.guildPoints.length === 0) {
                    this.pointIndex = 1;
                } else {
                    this.pointIndex = this.guildPoints[0].pointIndex + 1;
                }

                this.popup.close();
                this.xyzPopup.open();
            }, 300);
        });

        // 导线点-更新
        this.$$('#tunnel-update').on("click", async () => {
            _delay('tunnel-update', async () => {
                await this.forms('更新导线点', 'update');
                this.$$('#btn-tab-ruler').hide();

                for (const item of this.guildPoints) {
                    if (item.pointIndex === this.pointIndex) {
                        this.$$('#x').val(item.x);
                        this.$$('#y').val(item.y);
                        this.$$('#z').val(item.z);
                        this.currentId = item.id;
                        break;
                    }
                }

                this.popup.close();
                this.xyzPopup.open();
            }, 300);
        });

        // 导线点-插入
        this.$$('#tunnel-insert').on("click", async () => {
            _delay('tunnel-insert', async () => {
                await this.forms('插入导线点', 'insert');

                if (this.guildPoints.length === 0 || this.pointIndex === 0) {
                    this.toast('无法通过进尺插入导线点。');
                    this.$$('#btn-tab-ruler').hide();
                }

                this.popup.close();
                this.xyzPopup.open();
            }, 300);
        });

        // 导线点-删除
        this.$$('#tunnel-delete').on("click", async () => {
            _delay('tunnel-delete', async () => {
                this.status = 'delete';
                const data = await this.api.deleteTunnelPoint({
                    pointIndex: this.pointIndex,
                    pointIndexPrev: this.pointIndex -1,
                    tunnelCode: this.tunnelCode
                });
                if (data.code === 0) {
                    await this.refresh();
                    await this.init();
                }
            }, 300);
        });

        // 导线点-提交
        this.$$('#tunnel-submit').on("click", async () => {
            _delay('tunnel-submit', async () => {
                const gpt = {
                    pointIndex: this.pointIndex,
                    pointIndexPrev: this.pointIndex - 1,
                    tunnelCode: this.tunnelCode,
                    tunnelName: this.tunnelName,
                    mineCode: this.mineCode
                }

                const data = this.guildPoints;
                if (this.xyz === true) {
                    gpt.x = this.$$('#x').val();
                    gpt.y = this.$$('#y').val();
                    gpt.z = this.$$('#z').val();
                    if (this.status === 'update') {
                        gpt.id = this.currentId;
                        const resp = await this.api.updateTunnelPoint(gpt);
                        if (resp.code === 0) {
                            await this.refresh();
                            await this.init();
                        } else {
                            this.toast(resp.msg);
                        }
                    } else {
                        const resp = await this.api.insertTunnelPoint(gpt);
                        if (resp.code === 0) {
                            await this.refresh();
                            await this.init();
                        } else {
                            this.toast(resp.msg);
                        }
                    }
                } else {
                    const length = parseInt(this.$$('#ruler-length').val());
                    const elevation = parseInt(this.$$('#ruler-elevation').val());
                    const azimuth = parseInt(this.$$('#ruler-azimuth').val());
                    const classes = { 1: "早班", 2: "中班", 3: "晚班"};
                    const code = this.$$("#ruler-class").val();
                    const ruler = {
                        classesCode: code,
                        classesName: classes[code],
                        dateTime: this.$$("#ruler-time").val(),
                        description: "",
                        drivageRuler: length,
                        elevation: elevation,
                        azimuth: azimuth,
                        tunnelCode: this.tunnelCode,
                        tunnelName: this.tunnelName
                    }

                    // 向服务器添加进尺
                    const resp = await this.api.insertDrivageRuler(ruler);
                    this.toast(resp.msg);

                    // 进尺录入成功后,添加导线点
                    if (resp.code === 0) {
                        let pt = data[0];
                        if (this.status === 'insert' && this.pointIndex > 0) {
                            const index = this.pointIndex - 1;
                            for (let i = 0; i < data.length; i++) {
                                if (data[i].pointIndex === index) {
                                    pt = data[i];
                                    break;
                                }
                            }
                        }

                        const x = parseFloat(pt.x), y = parseFloat(pt.y);
                        const l = length * Math.cos(elevation / 180 * Math.PI);
                        gpt.x = x + l * Math.sin((azimuth / 180) * Math.PI);
                        gpt.y = y + l * Math.cos((azimuth / 180) * Math.PI);

                        const resp2 = await this.api.insertTunnelPoint(gpt);
                        if (resp2.code === 0) {
                            await this.refresh();
                            await this.init();
                        } else {
                            this.toast(resp2.msg);
                        }
                    }
                }

                this.xyzPopup.close();
                this.popup.open();
            }, 300);
        });

        // 导线点-取消编辑
        this.$$('#tunnel-cancel').on("click", async () => {
            this.xyzPopup.close();
            this.popup.open();
        });
    }

    tunnel() {
        this.$$("#tunnelshow").on("click", async () => {
            const config = this.algo.getConfig();
            if (config == null) {
                this.toast('请优先选择煤矿。');
                return;
            }

            this.tunnel = this.utils.getLocalStorage("tunnel");
            if (this.tunnel === null) {
                this.toast("没有设置巷道信息,请先选择巷道。");
                this.filter.init();
            } else {
                this.tunnelCode = this.tunnel.tunnelCode;
                this.$$("#work-area").html(this.tunnel.workfaceName);
                this.$$("#tunnel-name").html(this.tunnel.tunnelName);
                this.$$("#tunnel-width").html(this.tunnel.width);

                await this.init();
                this.popup = this.app.popup.create({ el: ".tunnel-popup" });
                this.popup.open();
            }

            // 当Filter发来选择完巷道的消息
            this.emitter.on("tunnel-filter-close", async () => {
                this.tunnel = this.utils.getLocalStorage("tunnel");
                this.tunnelCode = this.tunnel.tunnelCode;
                this.tunnelName = this.tunnel.tunnelName;
                this.$$("#work-area").html(this.tunnel.workfaceName);
                this.$$("#tunnel-name").html(this.tunnel.tunnelName);
                this.$$("#tunnel-width").html(this.tunnel.width);

                await this.init();
                this.popup = this.app.popup.create({ el: ".tunnel-popup" });
                this.popup.open();
            })

            this.$$("#tunnel-select").on("click", async () => {
                this.popup.close();
                this.filter.init();
            })
        })
    }

    template() {
        const tunnel_div = `
            <div class="popup tunnel-popup">
                <header>巷道信息管理</header>
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-label">工作面名称</div>
                                    <div class="item-inner">
                                        <span id="work-area"></span>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">巷道名称</div>
                                    <div class="item-inner">
                                        <span id="tunnel-name"></span>
                                        <span id="tunnel-select" style="cursor: pointer; color: orange;">切换巷道</span>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">巷道宽度(m)</div>
                                    <div class="item-inner">
                                        <span id="tunnel-width"></span>
                                    </div>
                                </div>
                            </li>
                        </ul>
                        <div class="card data-table" style="height: 360px;">
                            <table>
                                <thead>
                                <tr>
                                    <th class="numeric-cell">#</th>
                                    <th class="numeric-cell">x</th>
                                    <th class="numeric-cell">y</th>
                                    <th class="numeric-cell">z</th>
                                </tr>
                                </thead>
                                <tbody id="tunnel-table"></tbody>
                            </table>
                        </div>
                    </div>
                </article>
                <footer style="display: flex; justify-content: space-between; align-items: center; height: 60px;">
                    <div style="display: flex; justify-content: start; align-items: center;">
                        <button class="button button-fill color-primary  popup-open" id="tunnel-add">增加</button>
                        <button class="button button-fill color-primary  popup-open" id="tunnel-insert">插入</button>
                        <button class="button button-fill color-primary  popup-open" id="tunnel-update">更新</button>
                        <button class="button button-fill color-red" id="tunnel-delete">删除</button>
                    </div>
                    <div style="display: flex; justify-content: start; align-items: center;">
                        <button class="button button-fill color-gray popup-close" 
                            style="margin-right: 0; background: gray;">取消</button>
                    </div>
                </footer>
            </div>
        `;
        this.$$('#app').append(tunnel_div);

        const xyz_div = `
            <div class="popup xyz-popup" style="width: 460px; height: 460px;">
                <header id="popup-header">添加导线点</header>
                <article>
                    <div class="subnavbar">
                        <div class="subnavbar-inner">
                            <div class="segmented">
                                <a class="button tab-link tab-link-active" href="#tab-xyz" id="btn-tab-xyz">通过坐标添加</a>
                                <a class="button tab-link" href="#tab-ruler" id="btn-tab-ruler">通过进尺添加</a>
                            </div>
                        </div>
                    </div>
                    <div class="page-content hide-navbar-on-scroll">
                        <div class="tabs">
                            <div class="tab tab-active" id="tab-xyz">
                                <div class="block">
                                    <div class="list inline-labels no-hairlines-md">
                                        <ul>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">x</div>
                                                    <div class="item-input-wrap">
                                                        <label for="x">
                                                            <input type="text" value="" id="x"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">y</div>
                                                    <div class="item-input-wrap">
                                                        <label for="y">
                                                            <input type="text" value="" id="y"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">z</div>
                                                    <div class="item-input-wrap">
                                                        <label for="z">
                                                            <input type="text" value="" id="z"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="tab" id="tab-ruler">
                                <div class="block">
                                    <div class="list inline-labels no-hairlines-md">
                                        <ul>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">进尺(m)</div>
                                                    <div class="item-input-wrap">
                                                        <label for="ruler-length">
                                                            <input type="text" value="" id="ruler-length"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">仰角(°)</div>
                                                    <div class="item-input-wrap">
                                                        <label for="ruler-elevation">
                                                            <input type="text" value="" id="ruler-elevation"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">方位角(°)</div>
                                                    <div class="item-input-wrap">
                                                        <label for="ruler-azimuth">
                                                            <input type="text" value="" id="ruler-azimuth"
                                                                   required validate pattern="[0-9]*"
                                                                   data-error-message="仅能输入数字!">
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">录入时间</div>
                                                    <div class="item-input-wrap">
                                                        <label>
                                                            <input type="date" value="" placeholder="请选择时间..." id="ruler-time"
                                                            style="background: #dddddd !important; color: rgba(0, 0, 0, .65);"/>
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="item-content item-input">
                                                <div class="item-inner">
                                                    <div class="item-label">排班</div>
                                                    <div class="item-input-wrap">
                                                        <label for="ruler-class">
                                                            <select id="ruler-class">
                                                                <option value="1">早班</option>
                                                                <option value="2">中班</option>
                                                                <option value="3">晚班</option>
                                                            </select>
                                                        </label>
                                                    </div>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </article>
                <footer>
                    <button class="button button-fill color-primary popup-close" id="tunnel-submit">确定</button>
                    <button class="button button-fill color-gray popup-close" 
                        style="margin-right:0; background: gray;" id="tunnel-cancel">取消</button>
                </footer>
            </div>
        `;
        this.$$('#app').append(xyz_div);
    }

    control() {
        this.xyz();
        this.tunnel();
    }
}